package com.guo.todo.usercenter.service.session.impl;

import com.guo.todo.common.cache.CacheUtil;
import com.guo.todo.common.consts.CacheConst;
import com.guo.todo.common.consts.LoginConst;
import com.guo.todo.common.credential.Credential;
import com.guo.todo.common.excepiton.CommonException;
import com.guo.todo.usercenter.service.session.AbstractAAService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Transaction;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: hotlove_linx
 * @Date: 2023/7/19 22:29
 * @Description:
 */
@Service("redisSessionService")
public class RedisSessionServiceImpl extends AbstractAAService {


    @Override
    public void deleteSession(Credential credential) {

    }

    @Override
    public void invalidSession(Credential credential) {

    }

    @Override
    public void validAndFreshSession(Credential credential) throws CommonException {
        // 1.首先检查用户是否登录
        // 2.取登录的token与存储的token是否一致
        // 3.如果一致刷新token过期时间
        String tokenKey = "token-" + credential.getToken();

        if (CacheUtil.getInstance().exists(tokenKey)) {
            Map<String, String> profileMap = CacheUtil.getInstance().getMapValue(tokenKey);

            if (profileMap != null) {
                String profileId = MapUtils.getString(profileMap, "profileId");
                credential.setProfileId(Long.valueOf(profileId));

                String sessionKey = this.getSessionKey(credential);

                if (CacheUtil.getInstance().exists(sessionKey)) {

                    // 刷新key过期时间
                    // web登录
                    if (credential.getTerminal() == LoginConst.TERMINAL_WEB) {
                        CacheUtil.getInstance().expireKey(tokenKey, CacheConst.SESSION_TIMEOUT_MINUTE * 30);
                        CacheUtil.getInstance().expireKey(sessionKey, CacheConst.SESSION_TIMEOUT_MINUTE * 30);
                    } else {
                        CacheUtil.getInstance().expireKey(tokenKey, CacheConst.SESSION_TIMEOUT_DAY * 7);
                        CacheUtil.getInstance().expireKey(sessionKey, CacheConst.SESSION_TIMEOUT_DAY * 7);
                    }
                } else {
                    throw new CommonException("登录已过期，请重新登录系统");
                }
            } else {
                throw new CommonException("登录已过期，请重新登录系统");
            }
        } else {
            throw new CommonException("登录已过期，请重新登录系统");
        }
    }

    @Override
    public void registerSessionNormal(Credential credential) {
        jedisRegisterSession(credential);
    }

    @Override
    public void registerSessionIfUserNotAlive(Credential credential) {
        String sessionKey = getSessionKey(credential);

        try {
            if (CacheUtil.getInstance().exists(sessionKey)) {
                throw new CommonException("您的账号已经在别处登录，不能重复登录");
            }

            jedisRegisterSession(credential);

        } catch (CommonException e) {
            logger.info(e.getMessage());
        }
    }

    @Override
    public void registerSessionAndKickoutLastUser(Credential credential) {
        try {

            String sessionKey = getSessionKey(credential);

            // 如果session存在剔除之前的用户
            if (CacheUtil.getInstance().exists(sessionKey)) {

                // 剔除之前的登录信息
                String token = CacheUtil.getInstance().getValue(sessionKey);
                String tokenKey = "token-" + token;

                CacheUtil.getInstance().deleteKey(sessionKey);
                CacheUtil.getInstance().deleteKey(tokenKey);
            }

            jedisRegisterSession(credential);

        } catch (Exception exception) {
            logger.info(exception.getMessage());
        }
    }

    private String getSessionKey(Credential credential) {
        return "terminal-" + credential.getTerminal() + "-profileId-" +credential.getProfileId();
    }

    private void jedisRegisterSession(Credential credential) {

        CacheUtil cacheUtil = CacheUtil.getInstance();
        String tokenKey = "token-" + credential.getToken();
        String sessionKey = getSessionKey(credential);

        Map<String, String> profileMap = new HashMap<>();
        profileMap.put("profileId", credential.getProfileId() + "");
        profileMap.put("name", credential.getProfileName());
        profileMap.put("terminal", credential.getTerminal() + "");
        profileMap.put("token", credential.getToken());
        profileMap.put("loginTime", System.currentTimeMillis() + "");

        // 保存用户信息及登录session信息
        cacheUtil.execTx((obj) -> {
            Transaction tx = (Transaction) obj;

            tx.hset(tokenKey, profileMap);
            tx.set(sessionKey, credential.getToken());
            // web登录
            if (credential.getTerminal() == LoginConst.TERMINAL_WEB) {
                tx.expire(tokenKey, CacheConst.SESSION_TIMEOUT_MINUTE * 30);
                tx.expire(sessionKey, CacheConst.SESSION_TIMEOUT_MINUTE * 30);
            } else {
                tx.expire(tokenKey, CacheConst.SESSION_TIMEOUT_DAY * 7);
                tx.expire(sessionKey, CacheConst.SESSION_TIMEOUT_DAY * 7);
            }

            return null;
        });

    }
}
